/*
 * ******************************************************************************
 *   Copyright (c) 2013-2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.library.view;

import it.gmariotti.cardslib.library.Constants;
import it.gmariotti.cardslib.library.ResourceTable;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardCursorAdapter;
import it.gmariotti.cardslib.library.view.base.CardViewWrapper;
import it.gmariotti.cardslib.library.view.listener.SwipeOnScrollListener;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;

/**
 * Card List View.
 * It uses an {@link CardArrayAdapter} to populate items.
 * </p>
 * Usage:
 * It provides a default layout id for each row @layout/list_card_layout
 * Use can easily customize it using ohos:list_card_layout_resourceID attr in your xml layout.
 * </p>
 * Use this code to populate the list view
 * <pre><code>
 * CardListView listView = (CardListView) getAbility().findViewById(ResourceTable.Id_listId);
 * listView.setAdapter(mCardArrayAdapter);
 * </code></pre>
 * </p>
 * Currently you have to use the same inner layout for each card in listView.
 * </p>
 *
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class CardListView extends ListContainer implements CardViewWrapper.OnExpandListAnimatorListener {

    protected static String TAG = "CardListView";

    /**
     * Card Array Adapter
     */
    protected CardArrayAdapter mAdapter;

    /**
     * Card Cursor Adapter
     */
    protected CardCursorAdapter mCursorAdapter;

    /**
     * Custom ScrollListener to be used with a CardListView and cards with swipe action
     */
    protected SwipeOnScrollListener mOnScrollListener;


    //--------------------------------------------------------------------------
    // Custom Attrs
    //--------------------------------------------------------------------------

    /**
     * Default layout to apply to card
     */
    protected int list_card_layout_resourceID = ResourceTable.Layout_list_card_layout;

    //--------------------------------------------------------------------------
    // Constructors
    //--------------------------------------------------------------------------


    public CardListView(Context context) {
        super(context);
        init(null, "0");
    }

    public CardListView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(attrs, "0");
    }

    public CardListView(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    //--------------------------------------------------------------------------
    // Init
    //--------------------------------------------------------------------------

    /**
     * Initialize
     *
     * @param attrs
     * @param defStyle
     */
    protected void init(AttrSet attrs, String defStyle) {

        //Init attrs
        initAttrs(attrs, defStyle);

        //Set divider to 0dp
        //todo no such method
        //setDividerHeight(0);

    }


    /**
     * Init custom attrs.
     *
     * @param attrs
     * @param defStyle
     */
    protected void initAttrs(AttrSet attrs, String defStyle) {

        list_card_layout_resourceID = ResourceTable.Layout_list_card_layout;
        if (attrs.getAttr("list_card_layout_resourceID").isPresent()) {
            String s = attrs.getAttr("list_card_layout_resourceID").get().getStringValue();
            String id = s.split(":")[1];
            list_card_layout_resourceID = Integer.parseInt(id);
        }
    }

    //--------------------------------------------------------------------------
    // Adapter
    //--------------------------------------------------------------------------

    /**
     * Set the adapter. You can provide a {@link CardArrayAdapter}, or a {@link CardArrayAdapter}
     * or a generic adapter.
     * Pay attention: your generic adapter has to call {@link CardArrayAdapter#getComponent(int, Component, ComponentContainer)} method
     *
     * @param adapter
     */
    @Override
    public void setItemProvider(BaseItemProvider adapter) {
        if (adapter instanceof CardArrayAdapter) {
            setAdapter((CardArrayAdapter) adapter);
        } else if (adapter instanceof CardCursorAdapter) {
            setAdapter((CardCursorAdapter) adapter);
        } else {
            HiLog.warn(Constants.LABEL_LOG, TAG, "You are using a generic adapter. Pay attention: your adapter has to call cardArrayAdapter#getView method");
            super.setItemProvider(adapter);
        }
    }

    /**
     * Set {@link CardArrayAdapter} and layout used by items in ListView
     *
     * @param adapter {@link CardArrayAdapter}
     */
    public void setAdapter(CardArrayAdapter adapter) {
        super.setItemProvider(adapter);

        //Set Layout used by items
        adapter.setRowLayoutId(list_card_layout_resourceID);

        adapter.setCardListView(this);
        mAdapter = adapter;
    }

    /**
     * Set {@link CardCursorAdapter} and layout used by items in ListView
     *
     * @param adapter {@link CardCursorAdapter}
     */
    public void setAdapter(CardCursorAdapter adapter) {
        super.setItemProvider(adapter);

        //Set Layout used by items
        adapter.setRowLayoutId(list_card_layout_resourceID);

        adapter.setCardListView(this);
        mCursorAdapter = adapter;
    }

    /**
     * You can use this method, if you are using external adapters.
     * Pay attention. The generic adapter#getView() method has to call the cardArrayAdapter#getView() method to work.
     *
     * @param adapter          {@link BaseItemProvider} generic adapter
     * @param cardArrayAdapter {@link CardArrayAdapter} cardArrayAdapter
     */
    public void setExternalAdapter(BaseItemProvider adapter, CardArrayAdapter cardArrayAdapter) {

        setItemProvider(adapter);

        mAdapter = cardArrayAdapter;
        mAdapter.setCardListView(this);
        mAdapter.setRowLayoutId(list_card_layout_resourceID);
    }

    /**
     * You can use this method, if you are using external adapters.
     * Pay attention. The generic adapter#getView() method has to call the cardCursorAdapter#getView() method to work.
     *
     * @param adapter           {@link BaseItemProvider} generic adapter
     * @param cardCursorAdapter {@link CardCursorAdapter} cardArrayAdapter
     */
    public void setExternalAdapter(BaseItemProvider adapter, CardCursorAdapter cardCursorAdapter) {

        setItemProvider(adapter);

        mCursorAdapter = cardCursorAdapter;
        mCursorAdapter.setCardListView(this);
        mCursorAdapter.setRowLayoutId(list_card_layout_resourceID);
    }

    /**
     * Returns local scroll event listener
     * @return ScrolledListener
     */
    public ScrolledListener getOnScrollListener() {
        return this.mOnScrollListener;
    }

    /**
     * Overrides the set on scroll listener method and registers local reference
     *
     * @param mOnScrollListener
     */
    public void setOnScrollListener(ScrolledListener mOnScrollListener) {
        setScrolledListener(mOnScrollListener);
        if (mOnScrollListener instanceof SwipeOnScrollListener)
            this.mOnScrollListener = (SwipeOnScrollListener) mOnScrollListener;
    }

    //--------------------------------------------------------------------------
    // Expand and Collapse animator
    //--------------------------------------------------------------------------

    @Override
    public void onExpandStart(CardViewWrapper viewCard, Component expandingLayout) {

        boolean expandable = true;
        if (mCursorAdapter != null) {
            expandable = mCursorAdapter.onExpandStart(viewCard);
        }

        if (expandable)
            ExpandCollapseHelper.animateExpanding(expandingLayout, viewCard, this);

        if (mCursorAdapter != null) {
            mCursorAdapter.onExpandEnd(viewCard);
        }

    }

    @Override
    public void onCollapseStart(CardViewWrapper viewCard, Component expandingLayout) {
        boolean collapsible = true;
        if (mCursorAdapter != null) {
            collapsible = mCursorAdapter.onCollapseStart(viewCard);
        }

        if (collapsible)
            ExpandCollapseHelper.animateCollapsing(expandingLayout, viewCard, this);

        if (mCursorAdapter != null) {
            mCursorAdapter.onCollapseEnd(viewCard);
        }
    }


    /**
     * Helper to animate collapse and expand animation
     */
    private static class ExpandCollapseHelper {

        /**
         * This method expandes the view that was clicked.
         *
         * @param expandingLayout layout to expand
         * @param cardView        cardView
         * @param listView        listView
         */
        public static void animateCollapsing(final Component expandingLayout, final CardViewWrapper cardView, final ListContainer listView) {
            int origHeight = expandingLayout.getHeight();

            AnimatorValue animator = createHeightAnimator(expandingLayout, origHeight, 0);
            animator.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {

                }

                @Override
                public void onStop(Animator animator) {

                }

                @Override
                public void onCancel(Animator animator) {

                }

                @Override
                public void onEnd(Animator animator) {
                    expandingLayout.setVisibility(HIDE);

                    cardView.setExpanded(false);//card.setExpanded(true);

                    notifyAdapter(listView);

                    Card card = cardView.getCard();
                    if (card.getOnCollapseAnimatorEndListener() != null)
                        card.getOnCollapseAnimatorEndListener().onCollapseEnd(card);
                }

                @Override
                public void onPause(Animator animator) {

                }

                @Override
                public void onResume(Animator animator) {

                }
            });
            animator.start();
        }

        /**
         * This method collapse the view that was clicked.
         *
         * @param expandingLayout layout to collapse
         * @param cardView        cardView
         * @param listView        listView
         */
        public static void animateExpanding(final Component expandingLayout, final CardViewWrapper cardView, final ListContainer listView) {
            /* Update the layout so the extra content becomes visible.*/
            expandingLayout.setVisibility(VISIBLE);
            Component parent = (Component) expandingLayout.getComponentParent();
            //todo no such method
//            final int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth() - parent.getPaddingLeft() - parent.getPaddingRight(), View.MeasureSpec.AT_MOST);
//            final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
//            expandingLayout.measure(widthSpec, heightSpec);
            //todo 目前这个高度是我先死的，获取不到测量的高度
            AnimatorValue animator = createHeightAnimator(expandingLayout, 0, 400);
//            animator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
//                final int listViewHeight = listView.getHeight();
//                final int listViewBottomPadding = listView.getPaddingBottom();
//                final Component view = findDirectChild(expandingLayout, listView);
//
//                @Override
//                public void onUpdate(AnimatorValue animatorValue, float v) {
//                    final int bottom = view.getBottom();
//                    if (bottom > listViewHeight) {
//                        final int top = view.getTop();
//                        if (top > 0) {
//                            //listView.smoothScrollBy(Math.min(bottom - listViewHeight + listViewBottomPadding, top), 0);
//                            listView.scrollTo(Math.min(bottom - listViewHeight + listViewBottomPadding, top), 0);
//                        }
//                    }
//                }
//            });
            animator.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {

                }

                @Override
                public void onStop(Animator animator) {

                }

                @Override
                public void onCancel(Animator animator) {

                }

                @Override
                public void onEnd(Animator animator) {
                    cardView.setExpanded(true);//card.setExpanded(true);

                    notifyAdapter(listView);

                    Card card = cardView.getCard();
                    if (card.getOnExpandAnimatorEndListener() != null)
                        card.getOnExpandAnimatorEndListener().onExpandEnd(card);

                }

                @Override
                public void onPause(Animator animator) {

                }

                @Override
                public void onResume(Animator animator) {

                }
            });
            animator.start();
        }

        private static Component findDirectChild(final Component view, final ListContainer listView) {
            Component result = view;
            Component parent = (Component) result.getComponentParent();
            while (parent != listView) {
                result = parent;
//                parent = (Component) result.getComponentParent();
            }
            return result;
        }

        public static AnimatorValue createHeightAnimator(final Component view, final int start, final int end) {
            AnimatorValue animator = new AnimatorValue();
            animator.setValueUpdateListener((animatorValue, v) -> {
                int value;
                if (end > start) {
                    value = (int) (start + (end - start) * v);
                } else {
                    value = (int) (end + (start - end) * (1 - v));
                }

                LayoutConfig layoutParams = view.getLayoutConfig();
                layoutParams.height = value;
                view.setLayoutConfig(layoutParams);

            });
            return animator;
        }

        /**
         * This method notifies the adapter after setting expand value inside cards
         *
         * @param listView
         */
        public static void notifyAdapter(ListContainer listView) {

            if (listView instanceof CardListView) {

                CardListView cardListView = (CardListView) listView;
                if (cardListView.mAdapter != null) {
                    cardListView.mAdapter.notifyDataChanged();
                }
            }
        }
    }
}
